<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\admin\model\RouteModel;
use cmf\controller\AdminBaseController;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\portal\Tool\Tool;
use PHPExcel;
use PHPExcel_IOFactory;
use app\admin\model\ThemeModel;
use think\facade\Db;

class AdminLaorenController extends AdminBaseController
{

    /**
     * 页面管理
     * @adminMenu(
     *     'name'   => '页面管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '页面管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('portal_admin_page_index_view');

        if (!empty($content)) {
            return $content;
        }

        $param = $this->request->param();
        $xhpage    = $this->request->param('page', 1, 'intval');
        $pagenum = !empty($param['pagenum'])?$param['pagenum']:10;
        if($xhpage > 1){
            $xhpage = ($xhpage - 1)*$pagenum+1;
        } else {
            $xhpage = 1;
        }
        $this->assign('xhpage', $xhpage);
        $postService = new PostService();
        $data        = $postService->adminLaorenList($param);
        $data->appends($param);

        $ageArray = [];
        foreach ($data->toArray()['data'] as $item)
        {
            $zjnum = $item['more']['zjnum'];
            $birthday = substr($zjnum, 6, 8);
            $age = Tool::getYearsPassed($birthday);
            $ageArray[] = $age;
        }


        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
         $this->assign('zjnum', isset($param['zjnum']) ? $param['zjnum'] : '');
         $this->assign('pagenum', $pagenum);
        $this->assign('pages', $data->items());
        $this->assign('ageArray', $ageArray);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    /**
     * 工单录单选择残疾人管理
     * @adminMenu(
     *     'name'   => '页面管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '页面管理',
     *     'param'  => ''
     * )
     */
    public function gdlrlist()
    {
        $content = hook_one('portal_admin_page_index_view');

        if (!empty($content)) {
            return $content;
        }

        $param = $this->request->param();
        $xhpage    = $this->request->param('page', 1, 'intval');
        if($xhpage > 1){
            $xhpage = ($xhpage - 1)*10+1;
        } else {
            $xhpage = 1;
        }
        $this->assign('xhpage', $xhpage);

        $postService = new PostService();
        $data        = $postService->adminLaorenList($param);
        $data->appends($param);

        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('category', isset($param['category']) ? $param['category'] : '');
        $this->assign('pages', $data->items());
        $this->assign('page', $data->render());
        $this->assign('pageth', isset($param['page']) ? $param['page'] : '');

        return $this->fetch();
    }

    /**
     * 添加页面
     * @adminMenu(
     *     'name'   => '添加页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加页面',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $content = hook_one('portal_admin_page_add_view');

        if (!empty($content)) {
            return $content;
        }
        $timestamp = date("Ymd").mt_rand(1000,9999);
        $themeModel     = new ThemeModel();
        $pageThemeFiles = $themeModel->getActionThemeFiles('portal/Laoren/index');
        $this->assign('page_theme_files', $pageThemeFiles);
        $this->assign('bianhao', $timestamp);
        return $this->fetch();
    }

        /**
     * 充值页面
     * @adminMenu(
     *     'name'   => '添加页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加页面',
     *     'param'  => ''
     * )
     */
    public function chongzhi()
    {
        $content = hook_one('portal_admin_page_add_view');

        if (!empty($content)) {
            return $content;
        }
        $lrid    = $this->request->param('id', 0, 'intval');
        $portalPostModel = new PortalPostModel();
        $post            = $portalPostModel->where('id', $lrid)->find();
        $this->assign("lrid", $lrid);
        $this->assign('post', $post);
        return $this->fetch();
    }

    /**
     * 充值提交
     * @adminMenu(
     *     'name'   => '编辑页面提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面提交',
     *     'param'  => ''
     * )
     */
    public function addczPost()
    {
        $data = $this->request->param();
        //$this->error('充值');

        $result = $this->validate($data, 'AdminChongzhi');
        if ($result !== true) {
            $this->error($result);
        }

        $portalPostModel = new PortalPostModel();
        $data["money"] = $data["oldmoney"] + $data["addmoney"];
        $portalPostModel->adminEditChongzhi($data);
        //充值记录
        $chongzhi['user_id'] = cmf_get_current_admin_id();
        $chongzhi['create_time'] = time();
        $chongzhi['update_time'] = time();
        $chongzhi['published_time'] = time();
        $chongzhi['post_title'] = '用户（'.$data['post_title'].'）充值';
        $chongzhi['czlrid'] = $data["id"];
        $chongzhi['post_type'] = 4;
        $chongzhi['more'] = [
                                    'money' => $data["money"],
                                    'oldmoney' => $data["oldmoney"],
                                    'addmoney' => $data["addmoney"]
        ];
        Db::name('portal_post')->json(['more'])->insert($chongzhi);

        $this->success('充值成功', url('AdminLaoren/index'));

    }

    public function addhcPost()
    {
        $data = $this->request->param();
        //$this->error('红冲');

        $result = $this->validate($data, 'AdminChongzhi');
        if ($result !== true) {
            $this->error($result);
        }

        $portalPostModel = new PortalPostModel();
        $data["money"] = $data["oldmoney"] - $data["addmoney"];
        $portalPostModel->adminEditChongzhi($data);
        //充值记录
        $chongzhi['user_id'] = cmf_get_current_admin_id();
        $chongzhi['create_time'] = time();
        $chongzhi['update_time'] = time();
        $chongzhi['published_time'] = time();
        $chongzhi['post_title'] = '用户（'.$data['post_title'].'）红冲';
        $chongzhi['czlrid'] = $data["id"];
        $chongzhi['post_type'] = 4;
        $chongzhi['more'] = [
                                    'money' => $data["money"],
                                    'oldmoney' => $data["oldmoney"],
                                    'addmoney' => '-'.$data["addmoney"]
        ];
        Db::name('portal_post')->json(['more'])->insert($chongzhi);

        $this->success('红冲成功', url('AdminLaoren/czlist', ['id' => $data['id']]));

    }

        /**
     * 导入页面
     * @adminMenu(
     *     'name'   => '添加页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加页面',
     *     'param'  => ''
     * )
     */
    public function daoru()
    {
        $content = hook_one('portal_admin_page_add_view');

        
        return $this->fetch();
    }

    /**
     * 充值列表管理
     * @adminMenu(
     *     'name'   => '页面管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '页面管理',
     *     'param'  => ''
     * )
     */
    public function czlist()
    {
        $content = hook_one('portal_admin_page_index_view');

        if (!empty($content)) {
            return $content;
        }

        $param = $this->request->param();
        $lrid    = $this->request->param('id', 0, 'intval');

        $postService = new PostService();
        $data        = $postService->adminChongzhiList($param);

        foreach ($data as $datas) {
            $czinfo = Db::name('user')->where('id', $datas['user_id'])->find();
            $datas['user_name'] = $czinfo['user_nickname']?$czinfo['user_nickname']:$czinfo['user_login'];
        }
        $data->appends($param);

        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('pages', $data->items());
        $this->assign('page', $data->render());
        $this->assign("lrid", $lrid);
        $this->assign('start_time', $this->request->param('start_time'));
        $this->assign('end_time', $this->request->param('end_time'));

        return $this->fetch();
    }

    /**
     * 添加页面提交
     * @adminMenu(
     *     'name'   => '添加页面提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加页面提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        $data = $this->request->param();

        $result = $this->validate($data['post'], 'AdminPage');
        if ($result !== true) {
            $this->error($result);
        }

        if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
            $data['post']['more']['photos'] = [];
            foreach ($data['photo_urls'] as $key => $url) {
                $photoUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
            }
        }

        if (!empty($data['file_names']) && !empty($data['file_urls'])) {
            $data['post']['more']['files'] = [];
            foreach ($data['file_urls'] as $key => $url) {
                $fileUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
            }
        }


        $data['post']['post_type']   = 3;
        $portalPostModel = new PortalPostModel();

        $id_number = isset($data['post']['more']['zjnum']) ? $data['post']['more']['zjnum'] : '';
        if (!$id_number) {
            $this->error('请输入证件号码');
        }
        $count = $portalPostModel->whereLike('more', "%$id_number%")->count();
        if ($count) {
            $this->error('证件号码已存在');
        }

        $portalPostModel->adminAddArticle($data['post'], $data['post']['categories']);
        $this->success(lang('ADD_SUCCESS'), url('AdminLaoren/index'));

    }

    /**
     * 编辑页面
     * @adminMenu(
     *     'name'   => '编辑页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $content = hook_one('portal_admin_page_edit_view');

        if (!empty($content)) {
            return $content;
        }

        $id = $this->request->param('id', 0, 'intval');

        $portalPostModel = new PortalPostModel();
        $post            = $portalPostModel->where('id', $id)->find();
        $postCategories  = $post->categories()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));
        $flinfo = Db::name('portal_category')->where('id', $postCategoryIds)->find();
        $dlinfo = Db::name('portal_category')->where('id', $flinfo['parent_id'])->find();
        $themeModel     = new ThemeModel();
        $pageThemeFiles = $themeModel->getActionThemeFiles('portal/Laoren/index');

        $routeModel         = new RouteModel();
        $alias              = $routeModel->getUrl('portal/Laoren/index', ['id' => $id]);
        $post['post_alias'] = $alias;
        $this->assign('page_theme_files', $pageThemeFiles);
        $this->assign('post', $post);
        $this->assign('dlname', $dlinfo['name']);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);

        return $this->fetch();
    }

    /**
     * 编辑页面提交
     * @adminMenu(
     *     'name'   => '编辑页面提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        $data = $this->request->param();

        $result = $this->validate($data['post'], 'AdminPage');
        if ($result !== true) {
            $this->error($result);
        }

        if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
            $data['post']['more']['photos'] = [];
            foreach ($data['photo_urls'] as $key => $url) {
                $photoUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
            }
        }

        if (!empty($data['file_names']) && !empty($data['file_urls'])) {
            $data['post']['more']['files'] = [];
            foreach ($data['file_urls'] as $key => $url) {
                $fileUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
            }
        }
        $data['post']['post_type']   = 3;
        $portalPostModel = new PortalPostModel();

        $portalPostModel->adminEditArticle($data['post'], $data['post']['categories']);

        $this->success(lang('SAVE_SUCCESS'), url('AdminLaoren/index'));

    }

    /**
     * 删除页面
     * @author    iyting@foxmail.com
     * @adminMenu(
     *     'name'   => '删除页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除页面',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $portalPostModel = new PortalPostModel();
        $data            = $this->request->param();

        $result = $portalPostModel->adminDeletePage($data);
        if ($result) {
            $this->success(lang('DELETE_SUCCESS'));
        } else {
            $this->error(lang('DELETE_FAILED'));
        }

    }

     /**
     * 批量充值页面
     * @author    iyting@foxmail.com
     * @adminMenu(
     *     'name'   => '删除页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除页面',
     *     'param'  => ''
     * )
     */
    public function plcz()
    {
        $portalPostModel = new PortalPostModel();
        $czdata            = $this->request->param();
        if($czdata['plczmoney'] < 1) {
            $this->error('充值金额不能小于1元');
        }

        for($i=0;$i<count($czdata['ids']);$i++){
            //$this->success($czdata['ids'][$i]);
            $portalPostModel = new PortalPostModel();
            $czlrinfo            = $portalPostModel->where('id', $czdata['ids'][$i])->find();
            // Db::table('portal_post')
            //     ->where('id', $czdata['ids'][$i])
            //     ->inc('money', $czdata['plczmoney'])
            //     ->update();
            $data['id'] = $czdata['ids'][$i];
            $data["money"] = $czlrinfo["money"] + $czdata['plczmoney'];
            $portalPostModel->adminEditChongzhi($data);
            //充值记录
            $chongzhi['user_id'] = cmf_get_current_admin_id();
            $chongzhi['create_time'] = time();
            $chongzhi['update_time'] = time();
            $chongzhi['published_time'] = time();
            $chongzhi['post_title'] = '用户（'.$czlrinfo['post_title'].'）批量充值';
            $chongzhi['czlrid'] = $czdata['ids'][$i];
            $chongzhi['post_type'] = 4;
            $chongzhi['more'] = [
                                        'money' => $data["money"],
                                        'oldmoney' => $czlrinfo["money"],
                                        'addmoney' => $czdata['plczmoney']
            ];
            Db::name('portal_post')->json(['more'])->insert($chongzhi);
        }

        

        $this->success('充值成功');


    }

    /**
     * 清空所有残疾人余额
     * @author    iyting@foxmail.com
     * @adminMenu(
     *     'name'   => '删除页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除页面',
     *     'param'  => ''
     * )
     */
    public function qingkong()
    {
        $portalPostModel = new PortalPostModel();

        $data = Db::name('portal_post')->where('post_type', 3)->select();
        foreach ($data as $datas) {
            Db::name('portal_post')
                ->where('id', $datas['id'])
                ->update(['money' => 0]);
        }
        $this->success("清空成功");

    }

    /**
     * 清空个人残疾人余额
     *
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function qingkongById($id)
    {
        Db::name('portal_post')->where(['post_type' => 3, 'id' => $id])->update(['money' => 0]);
        $this->success('清空成功');

    }

    /**
     * 导出所有残疾人
     * @author    iyting@foxmail.com
     * @adminMenu(
     *     'name'   => '删除页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除页面',
     *     'param'  => ''
     * )
     */
    public function daochu()
    {
        
        //引入PHPExcel库文件
        //vendor("PHPExcel.PHPExcel");
        //创建对象
        $excel = new PHPExcel();
        //Excel表格式,这里简略写了8列
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G','H','I','J');
        //表头数组
        $tableheader = array('序号', '残疾人编号', '姓名', '性别', '年龄', '联系方式', '残疾等级','出生日期', '卡号', '余额');
        //填充表头信息
        for ($i = 0; $i < count($tableheader); $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }
        //表格数组
        // $data = array(
        //     array('1', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('2', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('3', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('4', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('5', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('6', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('7', 'B', 'C', 'D', 'E', 'F', 'G'),
        // );
        $portalPostModel = new PortalPostModel();

        $data2 = Db::name('portal_post')->where('post_type', 3)->where('delete_time', 0)->select();
        // foreach ($data as $datas) {
        //     Db::name('portal_post')
        //         ->where('id', $datas['id'])
        //         ->update(['money' => 0]);
        // }
        // $tz = M('taizhang');
        // $data2 = $tz->field('type',true)->select();
        // //print_r($data2);exit();
        // //填充表格信息
        for ($i = 2; $i <= count($data2) + 1; $i++) {
            $infoarr = json_decode($data2[$i-2]['more']);
            $excel->getActiveSheet()->setCellValue("$letter[0]$i", $data2[$i-2]['id']);
            $excel->getActiveSheet()->setCellValue("$letter[1]$i", $infoarr->bianma);
            $excel->getActiveSheet()->setCellValue("$letter[2]$i", $data2[$i-2]['post_title']);
            $excel->getActiveSheet()->setCellValue("$letter[3]$i", $infoarr->sex);
            $excel->getActiveSheet()->setCellValue("$letter[4]$i", $infoarr->age);
            $excel->getActiveSheet()->setCellValue("$letter[5]$i", $infoarr->tel);
            $excel->getActiveSheet()->setCellValue("$letter[6]$i", $infoarr->butietype);
            $excel->getActiveSheet()->setCellValue("$letter[7]$i", $infoarr->birthday);
            $excel->getActiveSheet()->setCellValue("$letter[8]$i", $infoarr->dbznum);
            $excel->getActiveSheet()->setCellValue("$letter[9]$i", $data2[$i-2]['money']);
        }

        //创建Excel输入对象
        $write = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="残疾人列表.xlsx"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
        
        $this->success("导出成功");

    }

    /**
     * 导入
     * @author    iyting@foxmail.com
     * @adminMenu(
     *     'name'   => '删除页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除页面',
     *     'param'  => ''
     * )
     */
    public function daorupost()
    {
        $file = $this->request->file('excel');
        
         if ($file) {
                
            $file_types = explode(".", $_FILES ['excel'] ['name']); // ["name"] => string(25) "excel文件名.xls"
            $file_type = $file_types [count($file_types) - 1];//xls后缀
            $file_name = $file_types [count($file_types) - 2];//xls去后缀的文件名
            /*判别是不是.xls文件，判别是不是excel文件*/
            if (strtolower($file_type) != "xls" && strtolower($file_type) != "xlsx") {
                $this->error("不是Excel文件，重新上传");
            }

            // $info = $file->move(ROOT_PATH . 'public' . DS . 'excel');//上传位置
            // $path = ROOT_PATH . 'public' . DS . 'excel' . DS;
            // $file_path = $path . $info->getSaveName();//上传后的EXCEL路径
            ///$file_path = \think\facade\Filesystem::putFile( 'topic', $file);
            //echo $file_path;//文件路径

            //获取上传的excel表格的数据，形成数组
            $reader = \PHPExcel_IOFactory::createReaderForFile($file);
            $excel = $reader->load($file);
            $sheet = $excel->getActiveSheet();
 
            $re  = $sheet->toArray();
            for($i=1;$i<count($re);$i++){
                //$this->error($re[1][0]);
                if($re[$i][0]){
                    $data['post']['more']['bianma'] = $re[$i][0];
                    $data['post']['post_title'] = $re[$i][1];
                    $data['post']['more']['sex'] = $re[$i][2];
                    $data['post']['more']['age'] = $re[$i][3];
                    $data['post']['more']['tel'] = $re[$i][4];               
                    $data['post']['more']['birthday'] = $re[$i][5];               
                    $data['post']['money'] = $re[$i][6];
                    $data['post']['more']['zjtype'] = $re[$i][7];
                    $data['post']['more']['zjnum'] = $re[$i][8];
                    $data['post']['more']['butietype'] = $re[$i][11];
                    $data['post']['more']['dbznum'] = $re[$i][12];
                    $data['post']['more']['zzmm'] = $re[$i][13];
                    $data['post']['more']['zongjiao'] = $re[$i][14];
                    $data['post']['more']['hunyin'] = $re[$i][15];
                    $data['post']['more']['poname'] = $re[$i][16];
                    $data['post']['more']['add'] = $re[$i][17];
                    $data['post']['more']['guoji'] = $re[$i][18];
                    $data['post']['more']['minzu'] = $re[$i][19];
                    $data['post']['more']['jiguan'] = $re[$i][20];
                    $data['post']['categories'] = $re[$i][9];
                    $data['post']['post_keywords'] = '';
                    if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                        $data['post']['more']['photos'] = [];
                        foreach ($data['photo_urls'] as $key => $url) {
                            $photoUrl = cmf_asset_relative_url($url);
                            array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                        }
                    }

                    if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                        $data['post']['more']['files'] = [];
                        foreach ($data['file_urls'] as $key => $url) {
                            $fileUrl = cmf_asset_relative_url($url);
                            array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                        }
                    }
                    $data['post']['post_type']   = 3;
                    $portalPostModel = new PortalPostModel();

                    $id_number = isset($data['post']['more']['zjnum']) ? $data['post']['more']['zjnum'] : '';
                    if (!$id_number) {
                        $this->error('失败：导入项缺失证件号码');
                    }
                    $count = $portalPostModel->whereLike('more', "%$id_number%")->count();
                    if ($count) {
                        $this->error('失败：导入证件号码已存在');
                    }

                    $portalPostModel->adminAddArticle($data['post'], $data['post']['categories']);

                }
            }
            $this->success("导入成功");
            
            
        } else {
            $this->error("请选择文件");
        }
            
        //print_r($file);exit();
    }

    /**
     * 服务残疾人统计
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function statistics()
    {
        $param = $this->request->param();
        $year = $this->request->param('year', date('Y'));

        $serviceType = $this->request->param('serviceType', '已服务');
        $olderType = $this->request->param('olderType', '');

        $startTime = strtotime($year . '-01-01 00:00:00');
        $endTime = strtotime($year . '-12-31 23:59:59');

        $xhpage = $this->request->param('page', 1, 'intval');
        $pagenum = !empty($param['pagenum']) ? $param['pagenum'] : 10;
        if ($xhpage > 1) {
            $xhpage = ($xhpage - 1) * $pagenum + 1;
        } else {
            $xhpage = 1;
        }
        $this->assign('xhpage', $xhpage);

        $portalPostModel = new PortalPostModel();
        $dataArray = [];
        if($serviceType == '已服务')
        {
            $portalPostModel = $portalPostModel->alias('a')
                ->join('portal_post b', 'JSON_UNQUOTE(JSON_EXTRACT(`a`.`more`, "$.zjnum")) = JSON_UNQUOTE(JSON_EXTRACT(`b`.`more`, "$.zjnum"))')
                ->join('portal_category_post pivot', 'pivot.post_id = b.id')
                ->join('portal_category c', 'pivot.category_id = c.id')
                ->where(['b.post_type' => 3])
                ->where(['b.delete_time' => 0])
                ->where(['a.post_type' => 5])
                ->where(['a.gdstatus' => '已完成'])
                ->field('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) AS id_card')
                ->where('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) is not null')
                ->where('a.delete_time', 0)
                ->where('a.published_time', '>=', $startTime)
                ->where('a.published_time', '<=', $endTime);
            if(!empty($olderType))
            {
                $portalPostModel = $portalPostModel->where('JSON_UNQUOTE(JSON_EXTRACT(b.`more`, "$.butietype")) like "' . $olderType . '%"');
            }
            if(!empty($param['category']))
            {
                $portalPostModel = $portalPostModel->where('c.id', $param['category']);
            }
            $data = $portalPostModel->group('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum"))')->order('id_card desc')
                ->paginate($pagenum);
            $dataArray = $data->toArray()['data'];
        }
        else
        {
            $portalPostModel = $portalPostModel->alias('a')
                ->join('portal_post b', 'JSON_UNQUOTE(JSON_EXTRACT(`a`.`more`, "$.zjnum")) = JSON_UNQUOTE(JSON_EXTRACT(`b`.`more`, "$.zjnum"))')
                ->join('portal_category_post pivot', 'pivot.post_id = b.id')
                ->join('portal_category c', 'pivot.category_id = c.id')
                ->where(['b.post_type' => 3])
                ->where(['b.delete_time' => 0])
                ->where(['a.post_type' => 5])
                ->where('a.gdstatus', '<>', '已完成')
                ->field('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) AS id_card')
                ->where('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) is not null')
                ->where('a.delete_time', 0)
                ->where('a.published_time', '>=', $startTime)
                ->where('a.published_time', '<=', $endTime);
            if(!empty($olderType))
            {
                $portalPostModel = $portalPostModel->where('JSON_UNQUOTE(JSON_EXTRACT(b.`more`, "$.butietype")) like "' . $olderType . '%"');
            }
            if(!empty($param['category']))
            {
                $portalPostModel = $portalPostModel->where('c.id', $param['category']);
            }
            $data = $portalPostModel->group('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum"))')->order('id_card desc')
                ->paginate($pagenum);
            $dataArray = $data->toArray()['data'];
        }

        $nameArray = [];
        $ageArray = [];
        $sexArray = [];
        $olderTypeArray = [];
        $telArray = [];
        $communityArray = [];
        $medicalInstitutionCountArray = [];
        $hairSalonCountArray = [];
        $cleaningCompanyCountArray = [];
        $serviceTotalCountArray = [];
        $consumptionAmountArray = [];
        $balanceArray = [];

        $portalPostModel = new PortalPostModel();
        foreach ($dataArray as $key => $item)
        {
            if($serviceType == '已服务')
            {
                $medicalInstitutionCount = 0;
                $hairSalonCount = 0;
                $cleaningCompanyCount = 0;
                $serviceTotalCount = 0;
                $consumptionAmount = 0;

                $subDataArray = $portalPostModel->alias('a')
                    ->join('ylpt_portal_post b', 'JSON_UNQUOTE(JSON_EXTRACT(`a`.`more`, "$.zjnum")) = JSON_UNQUOTE(JSON_EXTRACT(`b`.`more`, "$.zjnum"))')
                    ->join('portal_category_post pivot', 'pivot.post_id = b.id')
                    ->join('portal_category c', 'pivot.category_id = c.id')
                    ->where(['b.post_type' => 3])
                    ->where(['b.delete_time' => 0])
                    ->where('a.czlrid = b.id')
                    ->where('a.gdstatus', '已完成')
                    ->where('a.more', 'like', '%' . $item['id_card'] . '%')
                    ->where('a.delete_time', 0)
                    ->where('a.published_time', '>=', $startTime)
                    ->where('a.published_time', '<=', $endTime)
                    ->field('a.id, b.post_title, a.more, b.more as bmore, c.name as community, JSON_UNQUOTE(JSON_EXTRACT(`b`.`more`, "$.butietype")) AS butietype')
                    ->order('a.update_time desc')
                    ->select()->toArray();
                $nameArray[] = $subDataArray[0]['post_title'];
                $butietype = $subDataArray[0]['butietype'];
                $olderTypeArray[] = $butietype;
                $telArray[] = $subDataArray[0]['more']['tel'];
                $communityArray[] = $subDataArray[0]['community'];

                $zjnum = $subDataArray[0]['more']['zjnum'];
                $birthday = substr($zjnum, 6, 8);
                $age = Tool::getYearsPassed($birthday);
                $ageArray[] = $age;
                $sex = $subDataArray[0]['more']['sex'];
                $sexArray[] = $sex;

                $subDataArray2 = $portalPostModel
                    ->where('post_type', 3)
                    ->where('more', 'like', '%' . $item['id_card'] . '%')
                    ->where('delete_time', 0)
                    ->field('id')
                    ->find();
                $czlrid = $subDataArray2['id'];

                $subDataArray2 = $portalPostModel
                    ->where('post_type', 5)
                    ->where('gdstatus', '已完成')
                    ->where('czlrid', $czlrid)
                    ->where('published_time', '>=', $startTime)
                    ->where('published_time', '<=', $endTime)
                    ->where('delete_time', 0)
                    ->select()->toArray();

                foreach ($subDataArray2 as $subKey => $subItem)
                {
                    $post_title_type_array = $portalPostModel
                        ->where('post_title', $subItem['more']['mendian'])
                        ->where('post_type', 2)
                        ->field('post_title_type')
                        ->find()->toArray();
                    if(!empty($post_title_type_array))
                    {
                        switch($post_title_type_array['post_title_type'])
                        {
                            case '医疗机构':
                                ++$medicalInstitutionCount;
                                break;
                            case '理发机构':
                                ++$hairSalonCount;
                                break;
                            case '保洁公司':
                                ++$cleaningCompanyCount;
                                break;
                        }

                        ++$serviceTotalCount;
                    }

//                    if($item['id_card'] == '130704193704231218')
                    {
                        $id = $subItem['id'];
                        $post_title = $subItem['post_title'];
                        $post_title = '用户：（' . $post_title . '）在工单：（' . $id . '）的扣费';
                        $portalPost = $portalPostModel
                            ->where('post_title', $post_title)
                            ->where('published_time', '>=', $startTime)
                    		->where('published_time', '<=', $endTime)
                            ->find();
                        $addmoney = $portalPost['more']['addmoney'];
                        $consumptionAmount += $addmoney;
                    }
                }

                $medicalInstitutionCountArray[] = $medicalInstitutionCount;
                $hairSalonCountArray[] = $hairSalonCount;
                $cleaningCompanyCountArray[] = $cleaningCompanyCount;
                $serviceTotalCountArray[] = $serviceTotalCount;
                $consumptionAmountArray[] = abs($consumptionAmount);

                $id = $subDataArray[0]['id'];
                $post_title = $subDataArray[0]['post_title'];
                $post_title = '用户：（' . $post_title . '）在工单：（' . $id . '）的扣费';
                $portalPost = $portalPostModel
                    ->where('post_title', $post_title)
                    ->where('published_time', '>=', $startTime)
                    ->where('published_time', '<=', $endTime)
                    ->order('id desc')
                    ->find();
                $moneyId = $portalPost['id'];
                $money = $portalPost['more']['money'];

                $portalPost = $portalPostModel
                    ->where('more', 'like', '%' . $item['id_card'] . '%')
                    ->where('post_type', 3)
                    ->where('delete_time', 0)
                    ->order('update_time desc')
                    ->find();
                $czlrid = $portalPost['id'];

                $post_title = $subDataArray[0]['post_title'];
                $post_title = '用户（' . $post_title . '）批量充值';
                $portalPost = $portalPostModel
                    ->where('post_title', $post_title)
                    ->where('czlrid', $czlrid)
                    ->where('published_time', '>=', $startTime)
                    ->where('published_time', '<=', $endTime)
                    ->order('id desc')->find();
                $rechargeId = $portalPost['id'];
//                if($item['id_card'] == '130703194011150325')
                {
                    if($rechargeId > $moneyId)
                    {
                        $money = $portalPost['more']['money'];
                    }
                }
                $balanceArray[] = $money;
            }
            else
            {
                $subDataArray = $portalPostModel->alias('b')
                    ->join('portal_category_post pivot', 'pivot.post_id = b.id')
                    ->join('portal_category c', 'pivot.category_id = c.id')
                    ->where(['b.post_type' => 3])
                    ->where(['b.delete_time' => 0])
                    ->where('b.more', 'like', '%' . $item['id_card'] . '%')
                    ->where('b.delete_time', 0)
                    ->field('b.post_title, b.more, c.name as community')
                    ->order('b.update_time desc')
                    ->find();

                $nameArray[] = $subDataArray['post_title'];
                $olderTypeArray[] = $subDataArray['more']['butietype'];
                $telArray[] = $subDataArray['more']['tel'];
                $communityArray[] = $subDataArray['community'];

                $zjnum = $subDataArray['more']['zjnum'];
                $birthday = substr($zjnum, 6, 8);
                $age = Tool::getYearsPassed($birthday);
                $ageArray[] = $age;
                $sex = $subDataArray['more']['sex'];
                $sexArray[] = $sex;

                $medicalInstitutionCountArray[] = 0;
                $hairSalonCountArray[] = 0;
                $cleaningCompanyCountArray[] = 0;
                $serviceTotalCountArray[] = 0;
                $consumptionAmountArray[] = 0;

                $post_title = $subDataArray['post_title'];
                $post_title = '用户（' . $post_title . '）批量充值';
                $portalPost = $portalPostModel
                    ->where('post_title', $post_title)
                    ->where('published_time', '>=', $startTime)
                    ->where('published_time', '<=', $endTime)
                    ->order('id desc')->find();
                $money = $portalPost['more']['money'];
                $balanceArray[] = $money;
            }

        }

        $data->appends($param);

        $this->assign('serviceType', isset($param['serviceType']) ? $param['serviceType'] : '已服务');
        $this->assign('olderType', isset($param['olderType']) ? $param['olderType'] : '');
        $this->assign('year', $year);
        $this->assign('maxYear', date('Y'));
        $this->assign('pagenum', isset($param['pagenum']) ? $param['pagenum'] : 10);
        $this->assign('pages', $data->items());

        $this->assign('nameArray', $nameArray);
        $this->assign('ageArray', $ageArray);
        $this->assign('sexArray', $sexArray);
        $this->assign('olderTypeArray', $olderTypeArray);
        $this->assign('telArray', $telArray);
        $this->assign('communityArray', $communityArray);
        $this->assign('medicalInstitutionCountArray', $medicalInstitutionCountArray);
        $this->assign('hairSalonCountArray', $hairSalonCountArray);
        $this->assign('cleaningCompanyCountArray', $cleaningCompanyCountArray);
        $this->assign('serviceTotalCountArray', $serviceTotalCountArray);
        $this->assign('consumptionAmountArray', $consumptionAmountArray);
        $this->assign('balanceArray', $balanceArray);


        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 服务残疾人统计导出
     *
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function statisticsDaochu()
    {
        //引入PHPExcel库文件
        //vendor("PHPExcel.PHPExcel");
        //创建对象
        $excel = new PHPExcel();
        //Excel表格式,这里简略写了8列
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        //表头数组
        $tableheader = array('序号', '姓名', '残疾等级', '性别', '年龄', '身份证', '联系电话', '街道社区', '医疗机构', '理发机构', '保洁公司', '服务总次数', '消费金额', '余额');
        //填充表头信息
        for ($i = 0; $i < count($tableheader); $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }

        $param = $this->request->param();
        $year = $this->request->param('year', date('Y'));

        $serviceType = $this->request->param('serviceType', '已服务');
        $olderType = $this->request->param('olderType', '');

        $startTime = strtotime($year . '-01-01 00:00:00');
        $endTime = strtotime($year . '-12-31 23:59:59');

        $param['dcid'] = explode(',', $param['dcid']);
        foreach ($param['dcid'] as &$value) {
            $value = '"' . $value . '"';
        }
        $param['dcid'] = implode(',', $param['dcid']);



        $portalPostModel = new PortalPostModel();
        $dataArray = [];
        if($serviceType == '已服务')
        {
            $portalPostModel = $portalPostModel->alias('a')
                ->join('portal_post b', 'JSON_UNQUOTE(JSON_EXTRACT(`a`.`more`, "$.zjnum")) = JSON_UNQUOTE(JSON_EXTRACT(`b`.`more`, "$.zjnum"))')
                ->join('portal_category_post pivot', 'pivot.post_id = b.id')
                ->join('portal_category c', 'pivot.category_id = c.id')
                ->where(['b.post_type' => 3])
                ->where(['b.delete_time' => 0])
                ->where(['a.post_type' => 5])
                ->where(['a.gdstatus' => '已完成'])
                ->field('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) AS id_card')
                ->where('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) is not null')
                ->where('a.delete_time', 0)
                ->where('a.published_time', '>=', $startTime)
                ->where('a.published_time', '<=', $endTime)
                ->where('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) in ('.$param['dcid'].')');
            if(!empty($olderType))
            {
                $portalPostModel = $portalPostModel->where('JSON_UNQUOTE(JSON_EXTRACT(b.`more`, "$.butietype")) like "' . $olderType . '%"');
            }
            if(!empty($param['category']))
            {
                $portalPostModel = $portalPostModel->where('c.id', $param['category']);
            }
            $data = $portalPostModel->group('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum"))')->order('id_card desc')
                ->select();
            $dataArray = $data->toArray();
        }
        else
        {
            $portalPostModel = $portalPostModel->alias('a')
                ->join('portal_post b', 'JSON_UNQUOTE(JSON_EXTRACT(`a`.`more`, "$.zjnum")) = JSON_UNQUOTE(JSON_EXTRACT(`b`.`more`, "$.zjnum"))')
                ->join('portal_category_post pivot', 'pivot.post_id = b.id')
                ->join('portal_category c', 'pivot.category_id = c.id')
                ->where(['b.post_type' => 3])
                ->where(['b.delete_time' => 0])
                ->where(['a.post_type' => 5])
                ->where('a.gdstatus', '<>', '已完成')
                ->field('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) AS id_card')
                ->where('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) is not null')
                ->where('a.delete_time', 0)
                ->where('a.published_time', '>=', $startTime)
                ->where('a.published_time', '<=', $endTime)
                ->where('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum")) in ('.$param['dcid'].')');
            if(!empty($olderType))
            {
                $portalPostModel = $portalPostModel->where('JSON_UNQUOTE(JSON_EXTRACT(b.`more`, "$.butietype")) like "' . $olderType . '%"');
            }
            if(!empty($param['category']))
            {
                $portalPostModel = $portalPostModel->where('c.id', $param['category']);
            }
            $data = $portalPostModel->group('JSON_UNQUOTE(JSON_EXTRACT(a.`more`, "$.zjnum"))')->order('id_card desc')
                ->select();
            $dataArray = $data->toArray();
        }

        $nameArray = [];
        $ageArray = [];
        $sexArray = [];
        $olderTypeArray = [];
        $telArray = [];
        $communityArray = [];
        $medicalInstitutionCountArray = [];
        $hairSalonCountArray = [];
        $cleaningCompanyCountArray = [];
        $serviceTotalCountArray = [];
        $consumptionAmountArray = [];
        $balanceArray = [];

        $portalPostModel = new PortalPostModel();
        foreach ($dataArray as $key => $item)
        {
            if($serviceType == '已服务')
            {
                $medicalInstitutionCount = 0;
                $hairSalonCount = 0;
                $cleaningCompanyCount = 0;
                $serviceTotalCount = 0;
                $consumptionAmount = 0;

                $subDataArray = $portalPostModel->alias('a')
                    ->join('ylpt_portal_post b', 'JSON_UNQUOTE(JSON_EXTRACT(`a`.`more`, "$.zjnum")) = JSON_UNQUOTE(JSON_EXTRACT(`b`.`more`, "$.zjnum"))')
                    ->join('portal_category_post pivot', 'pivot.post_id = b.id')
                    ->join('portal_category c', 'pivot.category_id = c.id')
                    ->where(['b.post_type' => 3])
                    ->where(['b.delete_time' => 0])
                    ->where('a.czlrid = b.id')
                    ->where('a.gdstatus', '已完成')
                    ->where('a.more', 'like', '%' . $item['id_card'] . '%')
                    ->where('a.delete_time', 0)
                    ->where('a.published_time', '>=', $startTime)
                    ->where('a.published_time', '<=', $endTime)
                    ->field('a.id, b.post_title, a.more, b.more as bmore, c.name as community, JSON_UNQUOTE(JSON_EXTRACT(`b`.`more`, "$.butietype")) AS butietype')
                    ->order('a.update_time desc')
                    ->select()->toArray();
                $nameArray[] = $subDataArray[0]['post_title'];
                $butietype = $subDataArray[0]['butietype'];
                $olderTypeArray[] = $butietype;
                $telArray[] = $subDataArray[0]['more']['tel'];
                $communityArray[] = $subDataArray[0]['community'];

                $zjnum = $subDataArray[0]['more']['zjnum'];
                $birthday = mb_substr($zjnum, 6, 4) . mb_substr($zjnum, 10, 2)
                    . mb_substr($zjnum, 12, 2);
                $age = Tool::getYearsPassed($birthday);
                $ageArray[] = $age;
                $sex = $subDataArray[0]['more']['sex'];
                $sexArray[] = $sex;

                $subDataArray2 = $portalPostModel
                    ->where('post_type', 3)
                    ->where('more', 'like', '%' . $item['id_card'] . '%')
                    ->where('delete_time', 0)
                    ->field('id')
                    ->find();
                $czlrid = $subDataArray2['id'];

                $subDataArray2 = $portalPostModel
                    ->where('post_type', 5)
                    ->where('gdstatus', '已完成')
                    ->where('czlrid', $czlrid)
                    ->where('published_time', '>=', $startTime)
                    ->where('published_time', '<=', $endTime)
                    ->where('delete_time', 0)
                    ->select()->toArray();

                foreach ($subDataArray2 as $subKey => $subItem)
                {
                    $post_title_type_array = $portalPostModel
                        ->where('post_title', $subItem['more']['mendian'])
                        ->where('post_type', 2)
                        ->field('post_title_type')
                        ->find()->toArray();
                    if(!empty($post_title_type_array))
                    {
                        switch($post_title_type_array['post_title_type'])
                        {
                            case '医疗机构':
                                ++$medicalInstitutionCount;
                                break;
                            case '理发机构':
                                ++$hairSalonCount;
                                break;
                            case '保洁公司':
                                ++$cleaningCompanyCount;
                                break;
                        }

                        ++$serviceTotalCount;
                    }

//                    if($item['id_card'] == '130704193704231218')
                    {
                        $id = $subItem['id'];
                        $post_title = $subItem['post_title'];
                        $post_title = '用户：（' . $post_title . '）在工单：（' . $id . '）的扣费';
                        $portalPost = $portalPostModel
                            ->where('post_title', $post_title)
                            ->where('published_time', '>=', $startTime)
                            ->where('published_time', '<=', $endTime)
                            ->find();
                        $addmoney = $portalPost['more']['addmoney'];
                        $consumptionAmount += $addmoney;
                    }
                }

                $medicalInstitutionCountArray[] = $medicalInstitutionCount;
                $hairSalonCountArray[] = $hairSalonCount;
                $cleaningCompanyCountArray[] = $cleaningCompanyCount;
                $serviceTotalCountArray[] = $serviceTotalCount;
                $consumptionAmountArray[] = abs($consumptionAmount);

                $id = $subDataArray[0]['id'];
                $post_title = $subDataArray[0]['post_title'];
                $post_title = '用户：（' . $post_title . '）在工单：（' . $id . '）的扣费';
                $portalPost = $portalPostModel
                    ->where('post_title', $post_title)
                    ->where('published_time', '>=', $startTime)
                    ->where('published_time', '<=', $endTime)
                    ->order('id desc')
                    ->find();
                $moneyId = $portalPost['id'];
                $money = $portalPost['more']['money'];

                $portalPost = $portalPostModel
                    ->where('more', 'like', '%' . $item['id_card'] . '%')
                    ->where('post_type', 3)
                    ->where('delete_time', 0)
                    ->order('update_time desc')
                    ->find();
                $czlrid = $portalPost['id'];

                $post_title = $subDataArray[0]['post_title'];
                $post_title = '用户（' . $post_title . '）批量充值';
                $portalPost = $portalPostModel
                    ->where('post_title', $post_title)
                    ->where('czlrid', $czlrid)
                    ->where('published_time', '>=', $startTime)
                    ->where('published_time', '<=', $endTime)
                    ->order('id desc')->find();
                $rechargeId = $portalPost['id'];
//                if($item['id_card'] == '130703194011150325')
                {
                    if($rechargeId > $moneyId)
                    {
                        $money = $portalPost['more']['money'];
                    }
                }
                $balanceArray[] = $money;
            }
            else
            {
                $subDataArray = $portalPostModel->alias('b')
                    ->join('portal_category_post pivot', 'pivot.post_id = b.id')
                    ->join('portal_category c', 'pivot.category_id = c.id')
                    ->where(['b.post_type' => 3])
                    ->where(['b.delete_time' => 0])
                    ->where('b.more', 'like', '%' . $item['id_card'] . '%')
                    ->where('b.delete_time', 0)
                    ->field('b.post_title, b.more, c.name as community')
                    ->order('b.update_time desc')
                    ->find();

                $nameArray[] = $subDataArray['post_title'];
                $olderTypeArray[] = $subDataArray['more']['butietype'];
                $telArray[] = $subDataArray['more']['tel'];
                $communityArray[] = $subDataArray['community'];

                $zjnum = $subDataArray['more']['zjnum'];
                $birthday = mb_substr($zjnum, 6, 4) . mb_substr($zjnum, 10, 2)
                    . mb_substr($zjnum, 12, 2);
                $age = Tool::getYearsPassed($birthday);
                $ageArray[] = $age;
                $sex = $subDataArray['more']['sex'];
                $sexArray[] = $sex;

                $medicalInstitutionCountArray[] = 0;
                $hairSalonCountArray[] = 0;
                $cleaningCompanyCountArray[] = 0;
                $serviceTotalCountArray[] = 0;
                $consumptionAmountArray[] = 0;

                $post_title = $subDataArray['post_title'];
                $post_title = '用户（' . $post_title . '）批量充值';
                $portalPost = $portalPostModel
                    ->where('post_title', $post_title)
                    ->where('published_time', '>=', $startTime)
                    ->where('published_time', '<=', $endTime)
                    ->order('id desc')->find();
                $money = $portalPost['more']['money'];
                $balanceArray[] = $money;
            }

        }

        // //填充表格信息
        for ($i = 2; $i <= count($dataArray) + 1; $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[0]$i", $i - 1);
            $excel->getActiveSheet()->setCellValue("$letter[1]$i", $nameArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[2]$i", $olderTypeArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[3]$i", $sexArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[4]$i", $ageArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[5]$i",  "\xe2\x80\x8b" . $dataArray[$i - 2]['id_card']);
            $excel->getActiveSheet()->setCellValue("$letter[6]$i",  "\xe2\x80\x8b" . $telArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[7]$i", $communityArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[8]$i", $medicalInstitutionCountArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[9]$i", $hairSalonCountArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[10]$i", $cleaningCompanyCountArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[11]$i", $serviceTotalCountArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[12]$i", $consumptionAmountArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[13]$i", $balanceArray[$i - 2]);
        }
        //创建Excel输入对象
        $write = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="工单列表.xls"');
        header("Content-Transfer-Encoding:binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");

        $write->save('php://output');
        $this->success("导出成功");
    }

}
